package cn.ymxm.utils;

import cn.ymxm.entity.WechatPush;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/*
 * @Author Lzh
 * @Date 2022/8/24 22:45
 * @Description 工具集合
 * @Version 1.0
 **/
public class AllUtils {
    //此处获取各种信息均用的天行数据，如有特殊需求，请自行开发
    //https://www.tianapi.com/
    private static final String key = "xxxxxxxxxx";//填入自己的key

    /*
     * @Author Lzh
     * @Date 2022/8/24 22:45
     * @Description 获取天气，以及地区
     * @Version 1.0
     **/
    public static WechatPush getWeather() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        WechatPush wechatPush = new WechatPush();
        RestTemplate restTemplate = new RestTemplate();
        Map<String, String> map = new HashMap<String, String>();
        map.put("key", key);
        map.put("city", "370211");//最好填区域行政代码 身份证号前6位，此处以青岛做实验
        String res = restTemplate.getForObject(
                "https://api.tianapi.com/tianqi/index?key={key}&city={city}",
                String.class,
                map);
        JSONArray forecasts = JSONObject.parseObject(res).getJSONArray("newslist");
        JSONObject now = forecasts.getJSONObject(0);
        wechatPush.setArea(now.getString("area"));
        wechatPush.setDate(sdf.format(new Date()));
        wechatPush.setWeek(dateToWeek(sdf.format(new Date())));
        wechatPush.setWeather(now.getString("weather"));
        wechatPush.setLowTemp(now.getString("lowest"));
        wechatPush.setHighTemp(now.getString("highest"));
        wechatPush.setTemp(now.getString("real"));
        wechatPush.setWind(now.getString("wind"));
        wechatPush.setWindPower(now.getString("windsc"));
        return wechatPush;
    }

    /*
     * @Author Lzh
     * @Date 2022/8/24 22:45
     * @Description 获取每日英语
     * @Version 1.0
     **/
    public static Map<String, String> getDailyEnglish() {
        String httpUrl = "http://api.tianapi.com/ensentence/index?key=" + key;
        BufferedReader reader = null;
        String result = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                stringBuffer.append(strRead);
                stringBuffer.append("\r\n");
            }
            reader.close();
            result = stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray newslist = jsonObject.getJSONArray("newslist");
        String en = newslist.getJSONObject(0).getString("en");
        String zh = newslist.getJSONObject(0).getString("zh");
        Map<String, String> map = new HashMap<>();
        map.put("zh", zh);
        map.put("en", en);
        return map;
    }

    /*
     * @Author Lzh
     * @Date 2022/8/24 22:45
     * @Description 获取早安语句
     * @Version 1.0
     **/
    public static String getGoodMorning() {
        String httpUrl = "http://api.tianapi.com/zaoan/index?key=" + key;
        BufferedReader reader = null;
        String result = null;
        StringBuffer stringBuffer = new StringBuffer();
        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url
                    .openConnection();
            connection.setRequestMethod("GET");
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                stringBuffer.append(strRead);
                stringBuffer.append("\r\n");
            }
            reader.close();
            result = stringBuffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray newslist = jsonObject.getJSONArray("newslist");
        String content = newslist.getJSONObject(0).getString("content");
        return content;
    }

    /**
     * 获取纪念日差
     *
     * @param boyBirthday
     * @param girlBirthday
     * @param loveAnniversary
     * @return WechatPush
     */
    public static WechatPush getBirthdayAndLove(String boyBirthday, String girlBirthday, String loveAnniversary) {
        DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        WechatPush wechatPush = new WechatPush();
        try {
            wechatPush.setSinceBoyBirthday(calculationBirthday(boyBirthday));
            wechatPush.setSinceGirlBirthday(calculationBirthday(girlBirthday));
            wechatPush.setSinceLoveAnniversary((int) ((System.currentTimeMillis() - simpleDateFormat.parse(loveAnniversary).getTime()) / 86400000L));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wechatPush;
    }

    public static Integer calculationBirthday(String clidate) throws ParseException {
        SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cToday = Calendar.getInstance();
        Calendar cBirth = Calendar.getInstance();
        cBirth.setTime(myFormatter.parse(clidate));
        cBirth.set(Calendar.YEAR, cToday.get(Calendar.YEAR));
        int days;
        if (cBirth.get(Calendar.DAY_OF_YEAR) < cToday.get(Calendar.DAY_OF_YEAR)) {
            days = cToday.getActualMaximum(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
            days += cBirth.get(Calendar.DAY_OF_YEAR);
        } else {
            days = cBirth.get(Calendar.DAY_OF_YEAR) - cToday.get(Calendar.DAY_OF_YEAR);
        }
        if (days == 0) {
            return 0;
        } else {
            return days;
        }
    }

    /**
     * 根据日期获取 星期
     *
     * @param datetime
     * @return
     */
    public static String dateToWeek(String datetime) {
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        String[] weekDays = {"星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"};
        Calendar cal = Calendar.getInstance();
        Date date;
        try {
            date = f.parse(datetime);
            cal.setTime(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        //一周的第几天
        int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
        if (w < 0)
            w = 0;
        return weekDays[w];
    }


    public static void main(String[] args) {
        System.out.println(AllUtils.getWeather());
        System.out.println(AllUtils.getDailyEnglish());
        System.out.println(AllUtils.getGoodMorning());
    }
}
